package com.dxg.msns.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxg.msns.common.pojo.PageResult;
import com.dxg.msns.common.pojo.UserHistory;
import com.dxg.msns.common.pojo.UserHistoryDetailVO;
import com.dxg.msns.user.mapper.UserHistoryMapper;
import com.dxg.msns.user.service.UserHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 用户历史记录Service实现类
 */
@Service
public class UserHistoryServiceImpl implements UserHistoryService {

    @Autowired
    private UserHistoryMapper userHistoryMapper;

    /**
     * 添加或更新用户播放历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addOrUpdateUserHistory(UserHistory userHistory) {
        try {
            // 参数验证
            if (userHistory == null || StringUtils.isEmpty(userHistory.getUserId())
                    || StringUtils.isEmpty(userHistory.getMusicId())) {
                return "参数不能为空";
            }

            // 查询是否已存在该记录
            UserHistory existingHistory = userHistoryMapper.selectByUserIdAndMusicId(
                    userHistory.getUserId(), userHistory.getMusicId());

            if (existingHistory != null) {
                // 如果已存在，更新播放时间
                int updateResult = userHistoryMapper.updateCreateTimeByUserIdAndMusicId(
                        userHistory.getUserId(), userHistory.getMusicId());
                if (updateResult > 0) {
                    return "历史记录更新成功";
                } else {
                    return "历史记录更新失败";
                }
            } else {
                // 如果不存在，插入新记录
                if (userHistory.getCreateTime() == null) {
                    userHistory.setCreateTime(new Date());
                }
                int insertResult = userHistoryMapper.insert(userHistory);
                if (insertResult > 0) {
                    return "历史记录添加成功";
                } else {
                    return "历史记录添加失败";
                }
            }
        } catch (Exception e) {
            System.err.println("添加或更新用户历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return "操作失败：" + e.getMessage();
        }
    }

    /**
     * 分页查询用户历史记录
     */
    @Override
    public PageResult<UserHistory> queryUserHistoryByPage(String userId, Integer page, Integer rows) {
        try {
            // 参数验证
            if (StringUtils.isEmpty(userId)) {
                return new PageResult<>(0L, null);
            }

            if (page == null || page < 1) {
                page = 1;
            }
            if (rows == null || rows < 1) {
                rows = 10;
            }

            // 使用MyBatis-Plus分页查询
            Page<UserHistory> pageRequest = new Page<>(page, rows);

            QueryWrapper<UserHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.orderByDesc("create_time");

            IPage<UserHistory> historyPage = userHistoryMapper.selectPage(pageRequest, queryWrapper);

            return new PageResult<>(historyPage.getTotal(), historyPage.getRecords());

        } catch (Exception e) {
            System.err.println("分页查询用户历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return new PageResult<>(0L, null);
        }
    }

    /**
     * 查询用户所有历史记录（不分页）
     */
    @Override
    public List<UserHistory> queryUserHistoryAll(String userId) {
        try {
            if (StringUtils.isEmpty(userId)) {
                return null;
            }
            return userHistoryMapper.selectByUserIdOrderByTime(userId);
        } catch (Exception e) {
            System.err.println("查询用户所有历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据用户ID和音乐ID查询特定历史记录
     */
    @Override
    public UserHistory queryUserHistoryByUserIdAndMusicId(String userId, String musicId) {
        try {
            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(musicId)) {
                return null;
            }
            return userHistoryMapper.selectByUserIdAndMusicId(userId, musicId);
        } catch (Exception e) {
            System.err.println("查询特定历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 统计用户历史记录总数
     */
    @Override
    public Long countUserHistory(String userId) {
        try {
            if (StringUtils.isEmpty(userId)) {
                return 0L;
            }
            return userHistoryMapper.countByUserId(userId);
        } catch (Exception e) {
            System.err.println("统计用户历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 清空用户所有历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String clearUserHistory(String userId) {
        try {
            if (StringUtils.isEmpty(userId)) {
                return "用户ID不能为空";
            }

            int deleteResult = userHistoryMapper.deleteByUserId(userId);
            if (deleteResult >= 0) {
                return "清空历史记录成功，共删除 " + deleteResult + " 条记录";
            } else {
                return "清空历史记录失败";
            }
        } catch (Exception e) {
            System.err.println("清空用户历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return "清空失败：" + e.getMessage();
        }
    }

    /**
     * 删除特定的历史记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteUserHistory(String userId, String musicId) {
        try {
            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(musicId)) {
                return "用户ID和音乐ID不能为空";
            }

            QueryWrapper<UserHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("music_id", musicId);

            int deleteResult = userHistoryMapper.delete(queryWrapper);
            if (deleteResult > 0) {
                return "删除历史记录成功";
            } else {
                return "未找到要删除的历史记录";
            }
        } catch (Exception e) {
            System.err.println("删除特定历史记录异常：" + e.getMessage());
            e.printStackTrace();
            return "删除失败：" + e.getMessage();
        }
    }

    /**
     * 分页查询用户历史记录详情（包含音乐信息和收藏状态）
     */
    @Override
    public PageResult<UserHistoryDetailVO> queryUserHistoryDetailsWithPage(String userId, Integer page, Integer rows) {
        try {
            // 参数验证
            if (StringUtils.isEmpty(userId)) {
                return new PageResult<>(0L, null);
            }

            if (page == null || page < 1) {
                page = 1;
            }
            if (rows == null || rows < 1) {
                rows = 10;
            }

            // 计算偏移量
            Integer offset = (page - 1) * rows;

            // 查询详情数据
            List<UserHistoryDetailVO> detailList = userHistoryMapper.selectUserHistoryDetailsByPage(userId, offset,
                    rows);

            // 获取总数
            Long total = userHistoryMapper.countByUserId(userId);

            return new PageResult<>(total, detailList);

        } catch (Exception e) {
            System.err.println("分页查询用户历史记录详情异常：" + e.getMessage());
            e.printStackTrace();
            return new PageResult<>(0L, null);
        }
    }

    /**
     * 查询用户所有历史记录详情（包含音乐信息和收藏状态）
     */
    @Override
    public List<UserHistoryDetailVO> queryUserHistoryDetailsAll(String userId) {
        try {
            if (StringUtils.isEmpty(userId)) {
                return null;
            }
            return userHistoryMapper.selectUserHistoryDetailsAll(userId);
        } catch (Exception e) {
            System.err.println("查询用户所有历史记录详情异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}